/**
 * @module initWebSocket 初始化
 * @module websocketonopen 连接成功
 * @module websocketonerror 连接失败
 * @module websocketclose 断开连接
 * @module resetHeart 重置心跳
 * @module sendSocketHeart 心跳发送
 * @module reconnect 重连
 * @module sendMsg 发送数据
 * @module websocketonmessage 接收数据
 * @module test 测试收到消息传递
 * @description socket 通信
 * @param {any} url socket地址
 * @param {any} websocket websocket 实例
 * @param {any} heartTime 心跳定时器实例
 * @param {number} socketHeart 心跳次数
 * @param {number} HeartTimeOut 心跳超时时间
 * @param {number} socketError 错误次数
 */
import { useRouter } from "vue-router";
import { getToken } from "@/utils/auth";
import useNoticeStore from "@/store/modules/notice";
import { ElNotification } from "element-plus";
import axios from "axios";
import { setToken } from "@/utils/auth";
const { addNotice } = useNoticeStore();
const router = useRouter();
let socketUrl = ""; // socket地址
let websocket = null; // websocket 实例
let heartTime = null; // 心跳定时器实例
let socketHeart = 0; // 心跳次数
const HeartTimeOut = 10000; // 心跳超时时间 10000 = 10s
let socketError = 0; // 错误次数
let codeImg = "";
let senMessage = ref("");
// 初始化socket
export const initWebSocket = (url, token, clientId) => {
  if (import.meta.env.VITE_APP_WEBSOCKET === "false") {
    return;
  }
  if (!token || !clientId) {
    return;
  }
  socketUrl = url;
  // 初始化 websocket
  websocket = new WebSocket(
    url + "?Authorization=Bearer " + token + "&clientid=" + clientId
  );
  websocketonopen();
  websocketonmessage(token);
  websocketonerror();
  websocketclose();
  sendSocketHeart();
  return websocket;
};

// socket 连接成功
export const websocketonopen = () => {
  websocket.onopen = function () {
    resetHeart();
  };
};

// socket 连接失败
export const websocketonerror = () => {
  websocket.onerror = function (e) {
    // console.log("连接 websocket 失败", e);
  };
};

// socket 断开链接
export const websocketclose = () => {
  websocket.onclose = function (e) {
    // console.log("断开连接", e);
  };
};

// socket 重置心跳
export const resetHeart = () => {
  socketHeart = 0;
  socketError = 0;
  clearInterval(heartTime);
  sendSocketHeart();
};

// socket心跳发送
export const sendSocketHeart = () => {
  heartTime = setInterval(() => {
    // 如果连接正常则发送心跳
    if (websocket.readyState === 1) {
      // websocket.send(
      //   JSON.stringify({
      //     type: "ping",
      //   })
      // );
      socketHeart = socketHeart + 1;
    } else {
      // 重连
      reconnect();
    }
  }, HeartTimeOut);
};

// socket重连
export const reconnect = () => {
  if (socketError <= 2) {
    clearInterval(heartTime);
    initWebSocket(socketUrl);
    socketError = socketError + 1;
    // eslint-disable-next-line prettier/prettier
    // console.log("socket重连", socketError);
  } else {
    // eslint-disable-next-line prettier/prettier
    // console.log("重试次数已用完");
    clearInterval(heartTime);
  }
};

// socket 发送数据
export const sendMsg = (data) => {
  websocket.send(data);
};

// socket 接收数据
export const websocketonmessage = (token) => {
  websocket.onmessage = function (e) {
    if (e.data.indexOf("heartbeat") > 0) {
      resetHeart();
    }
    if (e.data.indexOf("ping") > 0) {
      return;
    }
    axios({
      url: "https://www.0934jzh.com/decor_blueprint/auth/downloadScanCode",
      method: "GET",
      headers: {
        Authorization: `Bearer ${token}`,
      },
      responseType: "arraybuffer",
    })
      .then((res) => {
        let u8a = new Uint8Array(res.data).reduce(
          (res, byte) => res + String.fromCharCode(byte),
          ""
        );
        codeImg = `${btoa(u8a)}`;
        localStorage.setItem("codeImage", codeImg);
        // return codeImg;
      })
      .catch((error) => {
        // console.log(error);
      });
    // console.log(e.data);
    try {
      const data = JSON.parse(e.data);
      if (data.msg === "扫码成功" && data.code === 200) {
        websocket.send(
          JSON.stringify({
            type: "Login",
            scene: data.scene,
          })
        );
      } else if (data.code == 500) {
        window.location.reload(); //重新建立连接，账号过期
      } else if (data.code === 501) {
        reconnect(); // 参数错误，用户需要重新扫码
        ElNotification({
          title: "消息",
          message: "请重新扫码",
          type: "error",
          duration: 3000,
        });
      }
      if (data.msg === "缓存成功" && data.code === "201") {
        axios({
          url: "https://www.0934jzh.com/decor_blueprint/auth/login?UUID=" + data.data,
          method: "GET",
          headers: {
            Authorization: `Bearer ${token}`,
          },
        })
          .then((res) => {
            if (res.data.code != 200) {
              ElNotification({
                title: "消息",
                message: res.data.msg,
                type: "error",
                duration: 3000,
              });
            } else {
              setToken(res.data.data.access_token);
              ElNotification({
                title: "消息",
                message: "登录成功",
                type: "success",
                duration: 3000,
              });
              router.push("/");
            }
          })
          .catch((error) => {
          });
      } else if (data.code == 500) {
        window.location.reload(); //重新建立连接，账号过期
      } else if (data.code === 501) {
        reconnect(); // 参数错误，用户需要重新扫码
        ElNotification({
          title: "消息",
          message: "请重新扫码",
          type: "error",
          duration: 3000,
        });
      }
    } catch (error) {}
    return e.data;
    // getCodeApi().then((res) => {
    //   let u8a = new Uint8Array(res).reduce(
    //     (res, byte) => res + String.fromCharCode(byte),
    //     ""
    //   );
    //   codeImg = `data:image/png;base64, ${btoa(u8a)}`;
    //   console.log('codeImg',codeImg)
    //   localStorage.setItem("codeImage", codeImg);
    //   return codeImg;
    // });
  };
};
